package com.example.demo.config;

import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.http.SessionCreationPolicy;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.security.web.SecurityFilterChain;
import org.springframework.web.cors.CorsConfigurationSource;

@Configuration
public class SecurityConfig {

    // 注入 CORS 配置源（来自之前的 CorsConfig）
    private final CorsConfigurationSource corsConfigurationSource;

    // 构造器注入 CORS 配置
    public SecurityConfig(CorsConfigurationSource corsConfigurationSource) {
        this.corsConfigurationSource = corsConfigurationSource;
    }

    @Bean
    public BCryptPasswordEncoder passwordEncoder() {
        return new BCryptPasswordEncoder();
    }

    @Bean
    public SecurityFilterChain securityFilterChain(HttpSecurity http) throws Exception {
        http
                // 1. 关键：关联 CORS 配置，使 Security 应用跨域规则
                .cors(cors -> cors.configurationSource(corsConfigurationSource))
                // 2. 禁用 CSRF（前后端分离+无状态认证场景）
                .csrf(csrf -> csrf.disable())
                // 3. 配置无状态会话（适合 JWT 等令牌认证）
                .sessionManagement(session -> session
                        .sessionCreationPolicy(SessionCreationPolicy.STATELESS)
                )
                // 4. 放行必要接口（如登录、注册）
                .authorizeHttpRequests(auth -> auth
                        .requestMatchers("/api/auth/**", "/api/products/**").permitAll()
                        .anyRequest().authenticated()
                );

        return http.build();
    }
}